package com.cinema.service;

import com.cinema.model.Movie;
import com.cinema.util.JsonFileStorage;
import java.util.*;

public class MovieService {
    private Map<String, Movie> movies;
    private static final String MOVIES_FILE = "data/movies.json";

    public MovieService() {
        loadMovies();
    }

    private void loadMovies() {
        try {
            movies = JsonFileStorage.loadFromFile(HashMap.class, MOVIES_FILE);
            if (movies == null) {
                movies = new HashMap<>();
                System.out.println("创建新的电影存储映射");
            }
        } catch (Exception e) {
            System.out.println("加载电影数据失败: " + e.getMessage());
            movies = new HashMap<>();
        }
    }

    private boolean saveMovies() {
        try {
            JsonFileStorage.saveToFile(movies, MOVIES_FILE);
            return true;
        } catch (Exception e) {
            System.out.println("保存电影数据失败: " + e.getMessage());
            return false;
        }
    }

    public boolean addMovie(Movie movie) {
        if (movies.containsKey(movie.getMovieId())) {
            System.out.println("电影ID已存在: " + movie.getMovieId());
            return false;
        }
        movies.put(movie.getMovieId(), movie);
        boolean success = saveMovies();
        if (success) {
            System.out.println("电影添加成功: " + movie.getTitle());
        }
        return success;
    }

    public boolean updateMovie(String movieId, Movie updatedMovie) {
        if (!movies.containsKey(movieId)) {
            System.out.println("电影不存在: " + movieId);
            return false;
        }
        movies.put(movieId, updatedMovie);
        return saveMovies();
    }

    public boolean deleteMovie(String movieId) {
        if (!movies.containsKey(movieId)) {
            System.out.println("电影不存在: " + movieId);
            return false;
        }
        movies.remove(movieId);
        return saveMovies();
    }

    public Movie getMovieById(String movieId) {
        return movies.get(movieId);
    }

    public List<Movie> getAllMovies() {
        return new ArrayList<>(movies.values());
    }

    public List<Movie> getShowingMovies() {
        List<Movie> showingMovies = new ArrayList<>();
        for (Movie movie : movies.values()) {
            if (movie.isShowing()) {
                showingMovies.add(movie);
            }
        }
        return showingMovies;
    }

    public List<Movie> searchMovies(String keyword) {
        List<Movie> results = new ArrayList<>();
        keyword = keyword.toLowerCase();

        for (Movie movie : movies.values()) {
            if (movie.getTitle().toLowerCase().contains(keyword) ||
                    movie.getDirector().toLowerCase().contains(keyword) ||
                    movie.getActors().toString().toLowerCase().contains(keyword)) {
                results.add(movie);
            }
        }
        return results;
    }
}
